import { createRouter, createWebHistory } from "vue-router";
import { localCache } from "@/utils/cache";
import { LOGIN_TOKEN } from "@/constants";
import {firstMenu} from "@/utils/mapMenus";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      redirect: "/main"
    },
    {
      path: "/main",
      name: "main",
      component: () => import("@/views/main/MainView.vue")
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/LoginView.vue")
    },
    {
      path: "/:pathMatch(.*)",
      name: "NotFound",
      component: () => import("@/views/not-found/NotFound.vue")
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.name !== "login" && !localCache.getCache(LOGIN_TOKEN)) next({ name: "login" });
  if (to.path === '/main') next({ path: firstMenu?.url });
  next();
});

export default router;
